package service

import (
	"context"
	"gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/go-base-sms/app/model"
	"gitee.com/zaiqiang231/go-base-sms/app/model/req"
	"gitee.com/zaiqiang231/go-base-sms/app/util"
	"strings"
	"time"
)

func SetWhite(ctx context.Context, request req.WhiteCreateRequest) (err error) {
	resultSet := store.GetRedisStore().Set(ctx, util.GetWhiteRedisKey(request.Phone), request.SmsCode, time.Duration(request.Timeout)*time.Second)
	err = resultSet.Err()
	return
}

func DeleteWhiteList(ctx context.Context, request req.WhiteListDelRequest) (err error) {
	keys := make([]string, 0)
	for i := 0; i < len(request.PhoneList); i++ {
		keys = append(keys, util.GetWhiteRedisKey(request.PhoneList[i]))
	}
	resultSet := store.GetRedisStore().Del(ctx, keys...)
	err = resultSet.Err()
	return
}

func GetWhiteList(ctx context.Context, request req.WhiteListRequest) (list []model.SmsWhiteInfo, finalScanLimit int64, cursor uint64, total int, hasMore bool, err error) {

	match := "sms:white:*"
	finalScanLimit = request.ScanLimit
	resultScan := store.GetRedisStore().Scan(ctx, request.Cursor, match, finalScanLimit)
	err = resultScan.Err()
	if err != nil {
		return
	}
	keys, cursor, err := resultScan.Result()

	if cursor != 0 && request.Cursor == 0 {
		for i := 0; i < 5; i++ {
			finalScanLimit = finalScanLimit * 2
			resultScan = store.GetRedisStore().Scan(ctx, request.Cursor, match, finalScanLimit)
			err = resultScan.Err()
			if err != nil {
				return
			}
			keys, cursor, err = resultScan.Result()
			if cursor == 0 {
				break
			}
		}
	}

	if err != nil {
		return
	}
	offset := (request.Page - 1) * request.PageSize
	if offset < 0 {
		offset = 0
	}
	tmpsize := 0
	total = len(keys)
	for i := offset; i < total; i++ {
		key := keys[i]
		dataType := store.GetRedisStore().Type(ctx, key).Val()
		smsCode := store.GetRedisStore().Get(ctx, key).Val()
		ttl := store.GetRedisStore().TTL(ctx, key).Val()
		var timeout int64
		if ttl == -1 {
			timeout = -1
		} else {
			timeout = int64(ttl / time.Second)
		}
		list = append(list, model.SmsWhiteInfo{
			DataType: dataType,
			Phone:    strings.Split(key, ":")[2],
			SmsCode:  smsCode,
			Timeout:  timeout,
		})
		tmpsize++
		if tmpsize == request.PageSize {
			break
		}
	}
	if len(list) == request.PageSize {
		hasMore = true
	}

	return
}
